//  温控策略
//  ZYDevicePolicyVC.m
//  YiLin
//
//  Created by Zyark on 2018/6/11.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYDevicePolicyVC.h"
#import "ZYCustomizeVC.h"
#import "UICurveView.h"
#import "ZYColorCheckButton.h"
#import "ZYCurve.h"
#import "ZYCurveViewModel.h"
#import "ZYModeTypeModel.h"
#import "ZYSocketMessageUtils.h"
#import "ZYDevice.h"
#import "ZYQuickSetupViewModel.h"
#import "UIColor+HTML.h"


@interface ZYDevicePolicyVC ()<UICurveViewDelegate>

@property(nonatomic,strong) NSArray *customValueArray;

@property(nonatomic,strong) UIScrollView *scrollView;

@property(nonatomic,strong) UIView *customizeBgView;

/**自定义*/
@property(nonatomic,strong) UICurveView *customizeCurveView;

/**
 系统推荐
 */
@property(nonatomic,strong) UILabel *systemLabel;

/**
 按钮组背景
 */
@property(nonatomic,strong) UIView *buttonBgView;

/**
 按钮组
 */
@property(nonatomic,strong) NSMutableArray *buttonArray;

/**
 曲线View
 */
@property(nonatomic,strong) UICurveView *curveView;

/**
 系统曲线
 */
@property(nonatomic,strong) NSArray *curveModels;


/**
 当前曲线类型
 */
@property(nonatomic,assign) ZYCurveType currentType;

/**
 选中底部线
 */
@property(nonatomic,strong) UIView *selectLine;

/**
 获取曲线值
 */
@property(nonatomic,strong) ZYCurveViewModel *viewModel;

/**
 快捷设置
 */
@property(nonatomic,strong) ZYQuickSetupViewModel *quickViewModel;

/**
 曲线是否开启
 */
@property(nonatomic,strong) NSArray *curveOpenArray;
@end

@implementation ZYDevicePolicyVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.title = [[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_HOME_EDIT_DEVICE_TEMPERATURE_CONTROL_STRATEGY];
    [self.viewModel.curveCommand execute:nil];
    [self.viewModel.getCustomCurveCommand execute:nil];
}

-(void)setup{
    [self setupView];
    [self bindView];
    ZYColorCheckButton *button = [_buttonArray firstObject];
    [self doSelectSysBtn:button];
}

-(void)setupView{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, ZYSCREEN_H - self.navigationView.bottom - SafeAreaBottomHeight)];
    _scrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_scrollView];
    _scrollView.alwaysBounceHorizontal = NO;
    _scrollView.alwaysBounceVertical = YES;
    _scrollView.top = self.navigationView.bottom;
    _scrollView.left = 0;
    if (@available(iOS 11.0, *)) {
        _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    ZYChangeLanguage *language = [ZYChangeLanguage sharedZYChangeLanguage];
    _systemLabel = [[UILabel alloc] init];
    _systemLabel.size = CGSizeMake(ZYSCREEN_W, 20);
    _systemLabel.textColor = kLabelColor;
    _systemLabel.font = [UIFont systemFontOfSize:18];
    _systemLabel.text = [language getStringByKey:LC_CURVE_TYPE_SYSTEM_LABEL];
    [_scrollView addSubview:_systemLabel];
    _systemLabel.top = 0;
    _systemLabel.left = 15;
    
    _buttonBgView = [[UIView alloc] init];
    _buttonBgView.size = CGSizeMake(ZYSCREEN_W - 30, 47);
    _buttonBgView.backgroundColor = RGBA(248, 248, 248, 1);
    _buttonBgView.layer.cornerRadius = 5;
    _buttonBgView.layer.masksToBounds = YES;
    [_scrollView addSubview:_buttonBgView];
    _buttonBgView.centerX = self.view.centerX;
    _buttonBgView.top = _systemLabel.bottom + 10;
    
    NSArray *titleArray = @[[language getStringByKey:LC_CURVE_TYPE_LABEL_AUTOMATIC_LEARNING],
                            [language getStringByKey:LC_CURVE_TYPE_LABEL_ELDERLY_CHILDREN],
                            [language getStringByKey:LC_CURVE_TYPE_SOUTH],
                            [language getStringByKey:LC_CURVE_TYPE_NORTH]];
    NSArray *curveTypeArray = @[[NSNumber numberWithUnsignedInteger:ZYCurveTypeAutomaticLearning],
                                [NSNumber numberWithUnsignedInteger:ZYCurveTypeElderlyChildren],
                                [NSNumber numberWithUnsignedInteger:ZYCurveTypeSouth],
                                [NSNumber numberWithUnsignedInteger:ZYCurveTypeNorth]];
    NSArray *colorStringArray = @[@"#faa4c9",@"#a8deff",@"#ebcdf3",@"#ceea95"];
    CGFloat btnWidth = _buttonBgView.width / 4;
    _buttonArray = [NSMutableArray arrayWithCapacity:4];
    for (NSInteger i=0; i<4; i++) {
        ZYColorCheckButton *button = [[ZYColorCheckButton alloc] initWithFrame:CGRectMake(i * btnWidth, 0, btnWidth, _buttonBgView.height)];
        button.title = [titleArray objectAtIndex:i];
        button.checkBackColor = [UIColor ColorFromHtml:[colorStringArray objectAtIndex:i]];
        button.textColor = [UIColor ColorFromHtml:@"#9d9d9d"];
        button.font = [UIFont systemFontOfSize:12];
        button.checkImage = [UIImage imageNamed:@"ic_policy_curve_btn_select"];
        button.tag = [[curveTypeArray objectAtIndex:i] integerValue];
        [button addTarget:self action:@selector(selectSysBtn:) forControlEvents:UIControlEventTouchUpInside];
        button.checked = NO;
        [_buttonBgView addSubview:button];
        [_buttonArray addObject:button];
    }
    
    //底部线条
    _selectLine = [[UIView alloc] initWithFrame:CGRectMake(0, _buttonBgView.height - 1, btnWidth - 1, 1)];
    _selectLine.backgroundColor = [UIColor ColorFromHtml:@"#FA967F"];
    [_buttonBgView addSubview:_selectLine];
    
    _curveView = [[UICurveView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W - ZYSCREEN_W * 0.16, 170)];
    _curveView.xChartBlock = ChartBlockMake(0, 3, 40, 8);
    _curveView.yChartBlock = ChartBlockMake(0, 5, 20, 6);
    _curveView.delegate = self;
    [_scrollView addSubview:_curveView];
    _curveView.centerX = self.view.centerX;
    _curveView.top = _buttonBgView.bottom + 8;
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, 1)];
    line.backgroundColor = RGBA(235, 235, 235, 1);
    [_scrollView addSubview:line];
    line.top = _curveView.bottom + 15;
    line.left = 0;
    
    _customizeBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, 60)];
    _customizeBgView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:_customizeBgView];
    _customizeBgView.top = line.bottom;
    _customizeBgView.left = 0;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doSetCustomize)];
    [_customizeBgView addGestureRecognizer:tap];
    
    UILabel *customizeLabel = [[UILabel alloc] init];
    customizeLabel.size = CGSizeMake(ZYSCREEN_W / 2, 20);
    customizeLabel.textColor = kLabelColor;
    customizeLabel.font = [UIFont systemFontOfSize:18];
    customizeLabel.text = [language getStringByKey:LC_CURVE_TYPE_CUSTOMIZE_LABEL];
    [_customizeBgView addSubview:customizeLabel];
    customizeLabel.centerY = _customizeBgView.height / 2;
    customizeLabel.left = 15;
    
    UIImageView *customizeRightImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic_curve_customize_right"]];
    [_customizeBgView addSubview:customizeRightImageView];
    customizeRightImageView.centerY = _customizeBgView.height / 2;
    customizeRightImageView.right = _customizeBgView.width - 15;
    
    UIView *customizeLine = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, 1)];
    customizeLine.backgroundColor = RGBA(235, 235, 235, 1);
    [_scrollView addSubview:customizeLine];
    customizeLine.top = _customizeBgView.bottom ;
    customizeLine.left = 0;
    
    _customizeCurveView = [[UICurveView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W - ZYSCREEN_W * 0.16, 170)];
    _customizeCurveView.xChartBlock = ChartBlockMake(0, 3, 40, 8);
    _customizeCurveView.yChartBlock = ChartBlockMake(0, 5, 20, 6);
    _customizeCurveView.delegate = self;
    [_scrollView addSubview:_customizeCurveView];
    _customizeCurveView.centerX = self.view.centerX;
    _customizeCurveView.top = _customizeBgView.bottom + 8;
    
    _scrollView.contentSize = CGSizeMake(0, _customizeBgView.bottom + 10 + SafeAreaBottomHeight);
    
}

//切换曲线
-(void)selectSysBtn:(id)sender
{
    ZYColorCheckButton *btn = (ZYColorCheckButton *)sender;
    if(btn.tag == _currentType){
        return;
    }
    [self doSelectSysBtn:btn];
}

-(void)doSelectSysBtn:(ZYColorCheckButton *)btn{
    NSLog(@"btn.tag:%ld",btn.tag);
    _currentType = btn.tag;
    
    NSInteger index = [_buttonArray indexOfObject:btn];
    CGFloat btnWidth = _buttonBgView.width / 4;
    CGRect frame = _selectLine.frame;
    frame.origin.x = index * btnWidth;
    
    [UIView animateWithDuration:0.3f animations:^{
        _selectLine.frame = frame;
    }];
    //重新排序曲线层次，并重新绘制
    NSMutableArray *_models = [NSMutableArray arrayWithArray:_curveModels];
    CurveModel *_tempModel;
    for (CurveModel *model in _curveModels) {
        if (model.type == btn.tag) {
            _tempModel = model;
            [_models removeObject:model];
        }
    }
    if(_tempModel){
        //将当前的曲线排在最前面
        [_models insertObject:_tempModel atIndex:0];
        _curveModels = [[_models reverseObjectEnumerator] allObjects];
        _curveView.curveItems = _curveModels;
    }
}

-(void)bindView{
    @weakify(self);
    [[self.viewModel.curveCommand.executionSignals switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        [self setupData:x];
    }];
    [self bindGetCustomCurve];
}

-(void)bindGetCustomCurve{
    @weakify(self);
    [[self.viewModel.getCustomCurveCommand.executionSignals switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        ZYCurve *curveInfo = x;
        CurveModel *curveitem;
        NSMutableArray *models = [[NSMutableArray alloc] init];
        NSMutableArray *hourTempures = [[NSMutableArray alloc] init];
        NSArray *values = [curveInfo.value componentsSeparatedByString:@","];
        NSInteger hour = 1;
        NSString *value = [values lastObject];
        [hourTempures addObject:[NSValue valueWithHourTempure:HourTempureValueMake(0, [value floatValue])]];
        for (NSString *value in values) {
            if(hour % 3 == 0){
                [hourTempures addObject:[NSValue valueWithHourTempure:HourTempureValueMake(hour / 3, [value floatValue])]];
            }
            hour ++;
        }
        curveitem = [[CurveModel alloc] init];
        curveitem.fillColor = [[UIColor ColorFromHtml:@"#19D892"] colorWithAlphaComponent:0.5];
        curveitem.lineColor = [UIColor ColorFromHtml:@"#19D892"];
        curveitem.name = curveInfo.name;
        curveitem.curveID = curveInfo.curveId;
        if(_device.type == ZYDeviceTypeRadiantFloorHeating){
            curveInfo.type = curveInfo.type - 4;
        }
        curveitem.type = curveInfo.type;
        curveitem.hourtempures = hourTempures;
        [models addObject:curveitem];
        self.customizeCurveView.curveItems = models;
    }];
}

-(void)setupData:(NSArray *)array{
    _curveModels = nil;
    _curveModels = [NSArray array];
    CurveModel *curveitem;
    NSMutableArray *models = [[NSMutableArray alloc] init];
    for (ZYCurve *curveInfo in array) {
        if(curveInfo.deviceType != _device.serverDeviceType){
            continue;
        }
        if(_device.type == ZYDeviceTypeRadiantFloorHeating){
            curveInfo.type = curveInfo.type - 4;
        }
        curveitem = [[CurveModel alloc] init];
        curveitem.name = curveInfo.name;
        curveitem.curveID = curveInfo.curveId;
        curveitem.type = curveInfo.type;
        switch (curveitem.type) {
            case ZYCurveTypeAutomaticLearning:
                curveitem.fillColor = [[UIColor ColorFromHtml:@"#faa4c9"] colorWithAlphaComponent:0.5];
                curveitem.lineColor = [UIColor ColorFromHtml:@"#faa4c9"];
                break;
            case ZYCurveTypeElderlyChildren:
                curveitem.fillColor = [[UIColor ColorFromHtml:@"#a8deff"] colorWithAlphaComponent:0.5];
                curveitem.lineColor = [UIColor ColorFromHtml:@"#a8deff"];
                break;
            case ZYCurveTypeSouth:
                curveitem.fillColor = [[UIColor ColorFromHtml:@"#ebcdf3"] colorWithAlphaComponent:0.5];
                curveitem.lineColor = [UIColor ColorFromHtml:@"#ebcdf3"];
                break;
            case ZYCurveTypeNorth:
                curveitem.fillColor = [[UIColor ColorFromHtml:@"#ceea95"] colorWithAlphaComponent:0.5];
                curveitem.lineColor = [UIColor ColorFromHtml:@"#ceea95"];
                break;
                
            default:
                break;
        }
        NSMutableArray *hourTempures = [[NSMutableArray alloc] init];
        NSArray *values = [curveInfo.value componentsSeparatedByString:@","];
        NSInteger hour = 1;
        NSString *value = [values lastObject];
        [hourTempures addObject:[NSValue valueWithHourTempure:HourTempureValueMake(0, [value floatValue])]];
        for (NSString *value in values) {
            if(hour % 3 == 0){
                [hourTempures addObject:[NSValue valueWithHourTempure:HourTempureValueMake(hour / 3, [value floatValue])]];
            }
            hour ++;
        }
        curveitem.hourtempures = hourTempures;
        [models addObject:curveitem];
    }
    _curveModels = models;
    _curveView.curveItems = _curveModels;
    if(_device.curveType == 0){
        ZYColorCheckButton *button = [_buttonArray firstObject];
        [self doSelectSysBtn:button];
    }else{
        BOOL isFind = NO;
        for (ZYColorCheckButton *button in _buttonArray) {
            button.checked = NO;
            if(button.tag == _device.curveType){
                button.checked = YES;
                [self doSelectSysBtn:button];
                isFind = YES;
            }
        }
        if(!isFind){
            ZYColorCheckButton *button = [_buttonArray firstObject];
            [self doSelectSysBtn:button];
        }
    }
    
}

#pragma mark -UICurveViewDelegate
//长按选中曲线
-(void)curveView:(UICurveView *)sender longPressed:(CurveModel *)model{
    NSLog(@"longpressed");
    if(sender == _curveView){
        for (ZYColorCheckButton *button in _buttonArray) {
            button.checked = NO;
            if(button.tag == model.type){
                button.checked = YES;
            }
        }
    }
    else{
        for (ZYColorCheckButton *button in _buttonArray) {
            button.checked = NO;
        }
        model.type = 5;//其他
        model.curveID = 0;
    }
    //设置曲线
    NSDictionary *dict = @{@"controlFlag":[NSNumber numberWithUnsignedInteger:model.type],@"curveId":[NSNumber numberWithInteger:model.curveID]};
    [ZYSocketMessageUtils setDeviceWithMac:_device.mac andParams:dict andCmd:5];
    [[ToastHelper sharedToastHelper] toastSuccess:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_SET_SUCCESS]];
}    

#pragma mark - event
-(void)doSetCustomize{
    //设置自定义曲线
    ZYCustomizeVC *vc = [[ZYCustomizeVC alloc] init];
    vc.device = _device;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Getter
-(ZYCurveViewModel *)viewModel{
    if(!_viewModel){
        _viewModel = [[ZYCurveViewModel alloc] init];
        _viewModel.macAddress = _device.mac;
    }
    return _viewModel;
}

-(ZYQuickSetupViewModel *)quickViewModel{
    if(!_quickViewModel){
        _quickViewModel = [[ZYQuickSetupViewModel alloc] init];
    }
    return _quickViewModel;
}

#pragma mark - socket
-(void)receiveMsgData:(device_communicate *)data{
    NSLog(@"data:%@",data);
    
}

@end
